/*
 * $Id: HttpPostTester.java,v 1.7 2009/07/28 19:23:57 afaichun Exp $
 *
 * Copyright (C) 2006 General Electric Company. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 *
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */

package com.ge.healthcare.autosc.onwatch.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.ge.healthcare.autosc.onwatch.util.OnWatchConstants;
/**
 * 
 * @author 212042946
 */
public class HttpPostTester {
    private static final String UPLOAD_URL =
    	"http://olc-asc-dev-01.am.health.ge.com:9702/asc-onwatch-web/OnWatchReceiver/fileUpload";
    private static final String DOWNLOAD_URL =
        "http://olc-asc-dev-01.am.health.ge.com:9701/asc-onwatch-web/OnWatchReceiver/fileDownload";
    private static final String HANDSHAKE_URL =
        "http://olc-asc-dev-01.am.health.ge.com:9701/asc-onwatch-web/OnWatchReceiver/handShake";
    
    public void testFileUpload() throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(UPLOAD_URL);
        
        MultipartEntity multipartEntity = new MultipartEntity(
        		HttpMultipartMode.BROWSER_COMPATIBLE);
        
        multipartEntity.addPart("systemId", new StringBody("ANTTSTIIP1"));
        //multipartEntity.addPart("systemId", new StringBody("ANTTSTIIP1"));
        //multipartEntity.addPart("mln", new StringBody("9999"));
        multipartEntity.addPart("iipVersion", new StringBody("4.0"));
        multipartEntity.addPart("requestType", new StringBody(OnWatchConstants.STATUSREPORT_REQUEST_TYPE));
        //multipartEntity.addPart("requestType", new StringBody(OnWatchConstants.PRODIAGS_REQUEST_TYPE));
        //multipartEntity.addPart("createdBy", new StringBody("TEST"));
        //multipartEntity.addPart("serviceId", new StringBody("PD_NS_01"));
        //multipartEntity.addPart("serviceDate", new StringBody("05/14/2009"));
        multipartEntity.addPart("checksum", new StringBody("3f80aeacf8b22b266c70d0373ae38639"));
        multipartEntity.addPart("taskId", new StringBody("1001"));
        //multipartEntity.addPart("modelType", new StringBody("LNX-09"));
        FileBody inFile1 = new FileBody(new File("D:/isd.properties"));
        multipartEntity.addPart("file", inFile1);
        
        httpPost.setEntity(multipartEntity);
        
        System.out.println("executing request " + httpPost.getRequestLine());
        
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();
        Header[] headers = response.getAllHeaders();
        for(Header header: headers) {
        	System.out.println("header name: " + header.getName() + ", header value: " + header.getValue());
        }
        System.out.println("Upload response content type: " + response.getEntity().getContentType());
        if (resEntity != null) {   
            String page = EntityUtils.toString(resEntity);   
            System.out.println("RESPONSE :" + page);   
        }   
    }
    
    
    public void testFileDownload() throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(DOWNLOAD_URL);
        
        List<NameValuePair> nvp = new ArrayList<NameValuePair>();
        nvp.add(new BasicNameValuePair("systemId", "ANTTSTIIP1"));
        nvp.add(new BasicNameValuePair("linkSecret", "hgecjcha474"));
        nvp.add(new BasicNameValuePair("iipVersion", "4.0"));
        nvp.add(new BasicNameValuePair("requestType", "download"));
        nvp.add(new BasicNameValuePair("taskId", "204"));
        nvp.add(new BasicNameValuePair("offset", "2"));
        nvp.add(new BasicNameValuePair("fileName", "supportFile2"));

        httpPost.setEntity(new UrlEncodedFormEntity(nvp, HTTP.UTF_8));
        
        System.out.println("executing request " + httpPost.getRequestLine());
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();   

        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	        if (resEntity != null) {
	        	String contentType = resEntity.getContentType().getValue();
	        	if(contentType != null) {
		        	if(contentType.startsWith("text/xml")) {
		        		System.out.println("Content type: " + resEntity.getContentType());
		                String page = EntityUtils.toString(resEntity);   
		                System.out.println("PAGE :" + page);
		        	} else {
		        		System.out.println("Content type: " + resEntity.getContentType());
			        	System.out.println("Downloading file...");
			        	File localFile = new File("/downloadedFile");
			        	InputStream in = null;
			        	OutputStream out = null;
			        	try {
			        		in = resEntity.getContent();
			        		out = new FileOutputStream(localFile);
			        		
			        		byte[] tmp = new byte[4096];
			        		int len;
			        		while ((len = in.read(tmp)) != -1) {
			        			out.write(tmp, 0, len);
			        		}
			        		out.flush();
			        	System.out.println("Download file done");	
			        	} finally {
			        		if(in != null) {
			        			in.close();
			        		}
			        		if(out != null) {
			        			out.close();
			        		}
			        		
			        	}
		        	}
	        	}
		    }
        } else {
	        if(resEntity != null) {
	        	String page = EntityUtils.toString(resEntity);   
	            System.out.println("PAGE :" + page);
	        	resEntity.consumeContent();
	        }
        }
    }
    
    public void testHandshake() throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(HANDSHAKE_URL);
        
        List<NameValuePair> nvp = new ArrayList<NameValuePair>();
        nvp.add(new BasicNameValuePair("systemId", "ANTTSTIIP1"));
        nvp.add(new BasicNameValuePair("linkSecret", "hgecjcha474"));
        nvp.add(new BasicNameValuePair("iipVersion", "4.0"));
        nvp.add(new BasicNameValuePair("requestType", "handShake"));
		nvp.add(new BasicNameValuePair("nextConnectTimeInSec", "100"));
		nvp.add(new BasicNameValuePair("registration", "false"));
		
        httpPost.setEntity(new UrlEncodedFormEntity(nvp, HTTP.UTF_8));
        System.out.println("executing request " + httpPost.getRequestLine());
        
        HttpResponse response = httpClient.execute(httpPost);
        Header[] headers = response.getAllHeaders();
        for(Header header: headers) {
        	System.out.println("header name: " + header.getName() + ", header value: " + header.getValue());
        }
        HttpEntity resEntity = response.getEntity();  
        System.out.println("Upload response content type: " + response.getEntity().getContentType());
        if (resEntity != null) {   
            String page = EntityUtils.toString(resEntity);   
            System.out.println("RESPONSE :\n" + page);   
        }
    }

    
    public static void main(String[] args) {
		HttpPostTester postTest = new HttpPostTester();
		try {
			//postTest.testFileUpload();
			postTest.testHandshake();
			//postTest.testFileDownload();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
    
}
